package record;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

import user.User;


public class DataStorage {
    private static final String USERS_FILE = "users.txt";


    public static boolean checkCredentials(String username,List<String> userRecords) {
        
        for (String record : userRecords) {
            String[] userInfo = record.split(",");
            if (userInfo[0].equals(username)) {
                return true;
            }
        }
        return false;
    }
    
    //注册
    public static int register(String username, String password,String telnumber,List<String> userRecords) {
        if (checkCredentials(username,userRecords)) {
            System.out.println("该用户名已被注册，请选择其他用户名。");
            return 0;
        }
        if (password.length() != 6) {
            System.out.println("密码必须为6位，请重新输入。");
            return -1;
        }

        User newUser = new User(username, password, telnumber);
        userRecords.add(formatRecord(newUser));
        saveUser(newUser);
       
        String path = username+"_number_records.txt";
        File file = new File(path);
        if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("系统错误"); 
                } // 如果文件不存在，则创建新文件
                System.out.println("File created successfully.");
        }
        return 1;
    }
    // 将新用户信息保存到文件中
    public static void saveUser(User user) {
        try  {
            BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                    new FileOutputStream(USERS_FILE),"UTF-8"));
            writer.write(user.getUsername() + "," + user.getPassword() + "," + user.getBalance()+"," + user.getTelnumber());
            writer.newLine();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //登录
    public static User loginUser(String username,String password,List<String> userRecords){
        for(String record:userRecords){
            String[] userInfo=record.split(",");
            if(userInfo[0].equals(username)&&userInfo[1].equals(password)){
                return new User(userInfo[0], userInfo[1], Double.parseDouble(userInfo[2]),userInfo[3]);
            }
        }
        return null; 
    }
    
  //更新余额
    public static void updateBalance(String username, double newBalance,List<String> userRecords) {
    	List<String> updatedRecords = new ArrayList<>();

        for (String record : userRecords) {
            String[] userInfo = record.split(",");
            if (userInfo[0].equals(username)) {
                // 更新特定用户的余额
                String updatedRecord = formatRecord(username, userInfo[1], newBalance,userInfo[3]);
                updatedRecords.add(updatedRecord);
            } else {
                updatedRecords.add(record);
            }
        }

        userRecords=updatedRecords;
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(USERS_FILE))) {
            for (String userRecord : userRecords) {
                writer.write(userRecord);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取全部用户信息
    public static List<String> readUserRecrods(){
    	List<String> records=new ArrayList<>();
        try{
            BufferedReader reader=new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(USERS_FILE),"UTF-8"));
            String line;
            while((line=reader.readLine())!=null){
                records.add(line);
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();  
        }
    	return records; 
  }

//生成某用户信息字符串
private static String formatRecord(String username,String password,double balance,String telnumber){     
        return username+","+password+","+balance+","+telnumber;  
  }  
private static String formatRecord(User user){     
    return user.getUsername()+","+user.getPassword()+","+user.getBalance()+","+user.getTelnumber();
    }  
    
    // 将购买记录保存到文件中
/*
    public static void savePurchaseRecord(NumbersRecord purchaseRecord) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(PURCHASE_RECORDS_FILE, true))) {
            writer.write(purchaseRecord.getUserNumber() + "," + purchaseRecord.getPurchaseTime() + "," + purchaseRecord.getPurchaseAmount());
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/
    

    // 将中奖记录保存到文件中
    /*
    public static void saveWinningRecord(WinningRecord winningRecord) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(WINNING_RECORDS_FILE, true))) {
            writer.write(winningRecord.getUserNumber() + "," + winningRecord.getWinningTime() + "," + winningRecord.getWinningAmount());
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/
/*
    // 根据用户号码查询购买记录
    public static List<NumbersRecord> getPurchaseRecordByUserNumber(String userNumber) {
        List<NumbersRecord> purchaseRecords = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(PURCHASE_RECORDS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] data = line.split(",");
                if (data[0].equals(userNumber)) {
                    NumbersRecord purchaseRecord = new NumbersRecord(userNumber, data[1], Double.parseDouble(data[2]));
                    purchaseRecords.add(purchaseRecord);
                }
            }
        } catch (IOException e) {        e.printStackTrace();
        }
        return purchaseRecords;
    }

    // 根据用户号码查询中奖记录
    public List<WinningRecord> getWinningRecordByUserNumber(String userNumber) {
        List<WinningRecord> winningRecords = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(WINNING_RECORDS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] data = line.split(",");
                if (data[0].equals(userNumber)) {
                    WinningRecord winningRecord = new WinningRecord(userNumber, data[1], Double.parseDouble(data[2]));
                    winningRecords.add(winningRecord);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return winningRecords;
    }*/
}
